<script setup lang="ts">
import type { UploadCustomRequestOptions} from 'naive-ui'
import {upload} from "@/apis/common";

const { modelValue, accept, maxNum = 1, download = false, text="上传文件", preview = false, disabled=false, listType="image-card" } = defineProps<{
  modelValue: string | undefined
  accept?: string
  maxNum?: number
  text?: string
  download?: boolean
  preview?: boolean
  disabled?: boolean
  listType?: "image-card" | "text" | "image"
}>()


const emit = defineEmits<{
  'update:modelValue': [string]
}>()

const imgUrl = computed({
  get() {
    return modelValue
  },
  set(value: string) {
    emit('update:modelValue', value)
  },
})


const customRequest = async ({ file }: UploadCustomRequestOptions) => {
  const formData = new FormData()
  formData.append('file', file.file as File)
  const res = await upload(formData);
  imgUrl.value = res.data.data
}
</script>

<template>
  <n-upload
    :list-type="listType"
    :accept="accept"
    class="relative rounded-2"
    :max="maxNum"
    :custom-request="customRequest"
    :show-download-button="download"
    :show-preview-button="preview"
    @remove="imgUrl = ''"
    :disabled="disabled"
  >
    <img v-if="imgUrl && listType === 'image-card'"  :src="imgUrl" class="w-full h-full rounded" :alt="text" />
  </n-upload>
</template>

<style scoped></style>
